#include "RDPTB.h"

int Get_String (FILE* instream, token_t* str)
{
    ASSERT (instream); ASSERT (str);

    printf ("Getting string.\n\n\n\n\n");

    while(1)
    {
        Get_Token (instream, str);

        if (str->type == EOF_TYPE) break;

        printf ("%d %lg\n", str->type, str->value);

        str++;
    }

    ASSERT (str);

    return 0;
}

int Get_Token (FILE* instream, token* str)
{
    ASSERT (instream);
    ASSERT (str);

    int res_input = 0;

    while (1)
    {
        if (Scan_For_Number (instream) == 1)
        {
            double number = 0;
            res_input = fscanf (instream, " %lg", &number);
            ASSERT (res_input);

            str->type = NUMBER;
            str->value = number;

            return 0;
        }
        else
        {
            int c = 0;

            c = fgetc (instream);

            if (isalpha (c)) toupper (c);

            switch (c)
            {
                case ADD:
                case SUB:
                case MUL:
                case DIV:
                    str->type = OPERATION;
                    str->value = c;
                    return 0;

                case X:
                    str->type = VARIABLE;
                    str->value = c;
                    return 0;

                case L_BR:
                case R_BR:
                    str->type = BRACKET;
                    str->value = c;
                    return 0;

                case DIFF:
                    str->type = DIFF_TYPE;
                    str->value = c;
                    return 0;

                case EOF:
                case '\n':
                    str->type = EOF_TYPE;
                    str->value = 0;
                    return 0;

                default:
                    printf ("Wrong token '%c'\n", c);
                    return TREE_ERR;
            }
        }
    }
}

int Scan_For_Number (FILE* instream)
{
    ASSERT (instream);

    int c = 0;

    while (isspace (c = getc (instream)));

    if (isdigit (c))
    {
        ungetc (c, instream);

        return 1;
    }

    int c1 = getc (instream);

    if ((c == '+' || c == '-') && isdigit (c1))
    {
        ungetc (c1, instream);
        ungetc (c, instream);

        return 1;
    }

    ungetc (c1, instream);
    ungetc (c, instream);

    return 0;
}
